package jd

import (
	"encoding/json"
	"fmt"
	"net/http"
	"net/http/cookiejar"
	//"reflect"
	"io/ioutil"
	"os"
	"strconv"
	"time"
)

var jdUrl = "http://www.jd.com/"
var loginUrl = "http://passport.jd.com/uc/login"
var submitLoginURL = "https://passport.jd.com/uc/loginService"

var provinesUrl = "http://easybuy.jd.com//address/getProvinces.action"
var cityUrl = "http://easybuy.jd.com//address/getCitys.action?provinceId="
var countUrl = "http://easybuy.jd.com//address/getCountys.action?cityId="

var gCurCookieJar *cookiejar.Jar

var filePath = "D:\\区域\\"

func GetStart() {

	str := `{"stat":{"pcode":"2810","pname":"大兴区","fname":"","size":"4"},"data":[{"code":"4194","name":"四环至五环之间"},{"code":"4205","name":"六环以外"},{"code":"6501","name":"五环至六环之间"},{"code":"51081","name":"亦庄经济开发区"}]}`
	fmt.Println(ToMap(str))

	nowTime := time.Now().Format("20060102150405")

	provineFile, provineErr := CreateFile("provine" + nowTime + ".txt")
	if provineErr != nil {
		fmt.Errorf("err=", provineErr)
	}
	defer provineFile.Close()
	cityFile, cityErr := CreateFile("city" + nowTime + ".txt")
	if cityErr != nil {
		fmt.Errorf("err=", cityErr)
	}
	defer cityFile.Close()
	countysFile, countysErr := CreateFile("countys" + nowTime + ".txt")
	if countysErr != nil {
		fmt.Errorf("err=", countysErr)
	}
	defer countysFile.Close()

	var cookie = "unpl=V2_ZzNsbUNeEBQmWkMEe0oMB2JUFgoSURYddVpPBHhLVAVlCkYNclRCFXEURlVnGVgUZwIZWUZcQxBFCHZXfx9sBWIzIl1BZ0IlfApOV30cVQRhMw%3D%3D; mt_subsite=|125%2C1444877713|; _tp=jRb2RwzqZBa024Cf%2BK8vkA%3D%3D; _pst=snxamdf; TrackID=1TnPBC6z0KamTk2yCPnty73vT1MZTdGKIov-ztZFuKRj5DFSl_5pVO4ATxeDo5FiFo8Q7tiwP1uXZR9WMrBl9_g; pinId=-c6el5mMNew; unick=snxamdfkhz; pin=snxamdf; thor=4F48483CC601B7BC6A938F8CB0A325B7E8091DB9F12F941DF8002BD7A5174799476FDC072C613B3CD11C43E60DF15A3D22739FFB335335FEB00260716B6652CF2B6DE291794057EFB8589EB5118856FF76DAE6D2F0446DF41F6B1388D7C7B052F445335E2FD6FD898E7031FCA7416081669BA7CD6A2009024782E79C6AA294B01CF1D914C8085D5D684B090F201AD221; __jda=122270672.839274807.1444875958.1444892222.1444959942.5; __jdb=122270672.4.839274807|5.1444959942; __jdc=122270672; __jdv=122270672|shengchan-email|edm_257_14|edm|08b0bc4a1ba34f5fa7d91c8a2c9138ea; __jdu=839274807"
	fmt.Println("cookie=", cookie)
	//获得省json
	//provine := getArea(provinesUrl,cookie)
	provine := `{"1":"北京","2":"天天"}`
	//time.Sleep(1 * time.Second)
	//解析省json
	//fmt.Println("provine=", provine)
	proMap := ToMap(provine)
	WriteAreaFile(provineFile, "root", "区域", proMap)
	fmt.Println("proMap=", proMap)
	for k1, v1 := range proMap {
		fmt.Println("\t", k1, "=", v1)
		time.Sleep(1 * time.Second)
		//获取市json
		//city := getArea(cityUrl+k1, cookie)
		city := `{"2810":"大兴区","2811":"小兴区"}`
		//解析市json
		//fmt.Println("\t", "city=", city)
		cityMap := ToMap(city)
		WriteAreaFile(cityFile, k1, v1.(string), cityMap)
		fmt.Println("\t", "cityMap=", cityMap)
		for k2, v2 := range cityMap {
			time.Sleep(1 * time.Second)
			fmt.Println("\t\t", k2, v2)
			//获得街道json
			//countys := getArea(countUrl+k2, cookie)
			countys := `{"6501":"五环至六环之间","51081":"亦庄经济开发区","4194":"四环至五环之间","4205":"六环以外"}`
			//解析街道json
			//fmt.Println("\t\t", "countys=", countys)
			countysMap := ToMap(countys)
			WriteAreaFile(countysFile, k2, v2.(string), countysMap)
			fmt.Println("\t\t", "countysMap=", countysMap)
			for k3, v3 := range countysMap {
				fmt.Println("\t\t\t", k3, v3)
			}
		}
	}
}
func Exist(fileName string) bool {
	_, err := os.Stat(fileName)
	return err == nil || os.IsExist(err)
}
func RemoveFile(fileName string) {
	//删除存在的文件
	if Exist(filePath + fileName) {
		os.Remove(filePath + fileName)
	}
}
func CreateFile(fileName string) (*os.File, error) {
	os.MkdirAll(filePath, 0777)
	return os.Create(filePath + fileName)
}
func WriteAreaFile(file *os.File, pcode, pname string, data map[string]interface{}) {
	var size = len(data)
	var i = 0
	var str string = `{"stat":{"pcode":"` + pcode + `","pname":"` + pname + `","fname":"","size":"` + strconv.Itoa(size) + `"},"data":[`
	for k, v := range data {
		str = str + `{"code":"` + k + `","name":"` + v.(string) + `"}`
		i++
		if i < size {
			str += ","
		}
	}
	str = str + `]}`
	file.WriteString(str)
	file.WriteString("\r\n")
	file.Sync()
}
func getArea(url, cookie string) string {
	httpClient := &http.Client{
		Jar: gCurCookieJar,
	}

	httpReq, _ := http.NewRequest("GET", url, nil)
	httpReq.Header.Add("Content-Type", "application/x-www-form-urlencoded")
	httpReq.Header.Add("Cookie", cookie)
	httpResp, err := httpClient.Do(httpReq)
	httpResp.Header.Add("Content-Type", "application/json;charset=UTF-8")
	if err != nil {
		fmt.Println("response error=", loginUrl, err.Error())
	}
	defer httpResp.Body.Close()
	body, err := ioutil.ReadAll(httpResp.Body)
	if err != nil {
		fmt.Println("get response for strUrl=", loginUrl, err.Error())
	}
	respHtml := string(body)
	return respHtml
}
func init() {
	gCurCookieJar, _ = cookiejar.New(nil)
}

func ToMap(data string) map[string]interface{} {
	var object interface{}
	json.Unmarshal([]byte(data), &object)
	//fmt.Println("provineData类型为=", reflect.TypeOf(object))
	if mmap, ok := object.(map[string]interface{}); ok {
		//fmt.Println("mmap=", mmap)
		return mmap
	}
	return make(map[string]interface{})
}
